<template>
  <div class="data-maintenance-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>数据维护管理</h1>
      <p class="subtitle">备份恢复、数据清理、维护任务管理</p>
    </div>

    <!-- 功能区块 -->
    <AppleGrid :columns="2" :gap="20">
      <!-- 备份管理区块 -->
      <AppleGridItem>
        <AppleCard title="备份管理" class="backup-section">
          <div class="section-content">
            <!-- 备份状态信息 -->
            <div class="backup-status">
              <div class="status-item">
                <span class="label">最近备份:</span>
                <span class="value" :class="getBackupStatusClass()">
                  {{ backupInfo.lastBackup || '未备份' }}
                </span>
              </div>
              <div class="status-item">
                <span class="label">备份数量:</span>
                <span class="value">{{ backupInfo.totalBackups || 0 }}</span>
              </div>
              <div class="status-item">
                <span class="label">总大小:</span>
                <span class="value">{{ formatFileSize(backupInfo.totalSize || 0) }}</span>
              </div>
            </div>

            <!-- 备份操作按钮 -->
            <div class="action-buttons">
              <AppleButton
                type="primary"
                :loading="backupLoading"
                @click="createBackup('full')"
                class="backup-btn"
              >
                <i class="icon-database"></i>
                完整备份
              </AppleButton>
              <AppleButton
                type="secondary"
                :loading="backupLoading"
                @click="createBackup('incremental')"
                class="backup-btn"
              >
                <i class="icon-refresh"></i>
                增量备份
              </AppleButton>
              <AppleButton
                type="outline"
                @click="showBackupList = true"
                class="backup-btn"
              >
                <i class="icon-list"></i>
                备份列表
              </AppleButton>
            </div>

            <!-- 自动备份设置 -->
            <div class="auto-backup-setting">
              <label class="setting-item">
                <input
                  type="checkbox"
                  v-model="autoBackupEnabled"
                  @change="updateAutoBackupSetting"
                />
                <span>启用自动备份</span>
              </label>
              <AppleSelect
                v-if="autoBackupEnabled"
                v-model="autoBackupInterval"
                :options="backupIntervalOptions"
                placeholder="备份频率"
                class="interval-select"
                @change="updateAutoBackupSetting"
              />
            </div>
          </div>
        </AppleCard>
      </AppleGridItem>

      <!-- 数据清理区块 -->
      <AppleGridItem>
        <AppleCard title="数据清理" class="cleanup-section">
          <div class="section-content">
            <!-- 清理统计 -->
            <div class="cleanup-stats">
              <div class="stat-item">
                <div class="stat-number">{{ cleanupStats.obsoleteRecords || 0 }}</div>
                <div class="stat-label">过期记录</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ cleanupStats.tempFiles || 0 }}</div>
                <div class="stat-label">临时文件</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ formatFileSize(cleanupStats.storageToFree || 0) }}</div>
                <div class="stat-label">可清理空间</div>
              </div>
            </div>

            <!-- 清理选项 -->
            <div class="cleanup-options">
              <label class="cleanup-option" v-for="option in cleanupOptions" :key="option.key">
                <input
                  type="checkbox"
                  v-model="selectedCleanupTypes"
                  :value="option.key"
                />
                <span class="option-text">
                  {{ option.label }}
                  <small v-if="option.description">({{ option.description }})</small>
                </span>
              </label>
            </div>

            <!-- 清理操作 -->
            <div class="cleanup-actions">
              <AppleButton
                type="warning"
                :loading="cleanupLoading"
                :disabled="selectedCleanupTypes.length === 0"
                @click="showCleanupConfirm = true"
                class="cleanup-btn"
              >
                <i class="icon-trash"></i>
                执行清理
              </AppleButton>
              <AppleButton
                type="outline"
                @click="analyzeCleanup"
                class="cleanup-btn"
              >
                <i class="icon-search"></i>
                分析预览
              </AppleButton>
            </div>
          </div>
        </AppleCard>
      </AppleGridItem>
    </AppleGrid>

    <!-- 维护历史区块 -->
    <AppleCard title="维护历史" class="maintenance-history">
      <div class="history-controls">
        <AppleSelect
          v-model="historyFilter"
          :options="historyFilterOptions"
          placeholder="操作类型"
          class="filter-select"
          @change="loadMaintenanceHistory"
        />
        <AppleButton
          type="outline"
          @click="loadMaintenanceHistory"
          class="refresh-btn"
        >
          <i class="icon-refresh"></i>
          刷新
        </AppleButton>
      </div>

      <AppleTable
        :columns="historyColumns"
        :data="maintenanceHistory"
        :loading="historyLoading"
        class="history-table"
      >
        <template #status="{ record }">
          <span :class="getStatusClass(record.status)">
            {{ getStatusText(record.status) }}
          </span>
        </template>
        <template #actions="{ record }">
          <AppleButton
            type="text"
            size="small"
            @click="viewMaintenanceDetail(record)"
          >
            查看详情
          </AppleButton>
          <AppleButton
            v-if="record.type === 'backup' && record.status === 'completed'"
            type="text"
            size="small"
            @click="restoreFromBackup(record)"
          >
            恢复
          </AppleButton>
        </template>
      </AppleTable>

      <ApplePagination
        v-model:current="currentPage"
        v-model:size="pageSize"
        :total="historyTotal"
        @change="loadMaintenanceHistory"
        class="history-pagination"
      />
    </AppleCard>

    <!-- 备份列表弹窗 -->
    <AppleModal
      v-model:visible="showBackupList"
      title="备份文件列表"
      width="800px"
      class="backup-list-modal"
    >
      <AppleTable
        :columns="backupListColumns"
        :data="backupList"
        :loading="backupListLoading"
      >
        <template #size="{ record }">
          {{ formatFileSize(record.size) }}
        </template>
        <template #actions="{ record }">
          <AppleButton
            type="text"
            size="small"
            @click="downloadBackup(record)"
          >
            下载
          </AppleButton>
          <AppleButton
            type="text"
            size="small"
            @click="restoreFromBackup(record)"
          >
            恢复
          </AppleButton>
          <AppleButton
            type="text"
            size="small"
            danger
            @click="deleteBackup(record)"
          >
            删除
          </AppleButton>
        </template>
      </AppleTable>
    </AppleModal>

    <!-- 清理确认弹窗 -->
    <AppleModal
      v-model:visible="showCleanupConfirm"
      title="确认数据清理"
      width="500px"
      class="cleanup-confirm-modal"
    >
      <div class="confirm-content">
        <div class="warning-icon">⚠️</div>
        <p class="warning-text">
          您即将执行数据清理操作，这将永久删除选中的数据。
          <br />
          请确认您已经做好了备份。
        </p>
        <div class="cleanup-summary">
          <p><strong>清理内容：</strong></p>
          <ul>
            <li v-for="type in selectedCleanupTypes" :key="type">
              {{ getCleanupTypeLabel(type) }}
            </li>
          </ul>
        </div>
      </div>
      <template #footer>
        <AppleButton @click="showCleanupConfirm = false">取消</AppleButton>
        <AppleButton
          type="danger"
          :loading="cleanupLoading"
          @click="executeCleanup"
        >
          确认清理
        </AppleButton>
      </template>
    </AppleModal>

    <!-- 恢复确认弹窗 -->
    <AppleModal
      v-model:visible="showRestoreConfirm"
      title="确认数据恢复"
      width="500px"
      class="restore-confirm-modal"
    >
      <div class="confirm-content">
        <div class="warning-icon">⚠️</div>
        <p class="warning-text">
          数据恢复将覆盖当前数据库中的所有数据。
          <br />
          建议在恢复前先创建当前数据的备份。
        </p>
        <div class="backup-info">
          <p><strong>备份文件：</strong>{{ selectedBackup?.filename }}</p>
          <p><strong>创建时间：</strong>{{ selectedBackup?.created_at }}</p>
          <p><strong>文件大小：</strong>{{ formatFileSize(selectedBackup?.size || 0) }}</p>
        </div>
        <label class="restore-option">
          <input type="checkbox" v-model="createBackupBeforeRestore" />
          <span>恢复前自动创建当前数据备份</span>
        </label>
      </div>
      <template #footer>
        <AppleButton @click="showRestoreConfirm = false">取消</AppleButton>
        <AppleButton
          type="danger"
          :loading="restoreLoading"
          @click="executeRestore"
        >
          确认恢复
        </AppleButton>
      </template>
    </AppleModal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useMessage } from '@/composables/useMessage'
import { dataMaintenanceApi } from '@/api/system'
import AppleCard from '@/components/ui/AppleCard.vue'
import AppleButton from '@/components/ui/AppleButton.vue'
import AppleSelect from '@/components/ui/AppleSelect.vue'
import AppleTable from '@/components/ui/AppleTable.vue'
import AppleModal from '@/components/ui/AppleModal.vue'
import ApplePagination from '@/components/ui/ApplePagination.vue'
import AppleGrid from '@/components/layout/AppleGrid.vue'
import AppleGridItem from '@/components/layout/AppleGridItem.vue'
import type { 
  BackupInfo, 
  CleanupStats, 
  MaintenanceRecord,
  BackupRecord,
  CleanupOption
} from '@/types/system'

// 响应式数据
const backupInfo = reactive<BackupInfo>({
  lastBackup: '',
  totalBackups: 0,
  totalSize: 0
})

const cleanupStats = reactive<CleanupStats>({
  obsoleteRecords: 0,
  tempFiles: 0,
  storageToFree: 0
})

const maintenanceHistory = ref<MaintenanceRecord[]>([])
const backupList = ref<BackupRecord[]>([])

// 加载状态
const backupLoading = ref(false)
const cleanupLoading = ref(false)
const restoreLoading = ref(false)
const historyLoading = ref(false)
const backupListLoading = ref(false)

// 弹窗显示状态
const showBackupList = ref(false)
const showCleanupConfirm = ref(false)
const showRestoreConfirm = ref(false)

// 表单数据
const autoBackupEnabled = ref(false)
const autoBackupInterval = ref('daily')
const selectedCleanupTypes = ref<string[]>([])
const historyFilter = ref('all')
const currentPage = ref(1)
const pageSize = ref(20)
const historyTotal = ref(0)
const selectedBackup = ref<BackupRecord | null>(null)
const createBackupBeforeRestore = ref(true)

// 配置选项
const backupIntervalOptions = [
  { label: '每日', value: 'daily' },
  { label: '每周', value: 'weekly' },
  { label: '每月', value: 'monthly' }
]

const cleanupOptions: CleanupOption[] = [
  { key: 'logs', label: '系统日志', description: '7天前的日志文件' },
  { key: 'temp_files', label: '临时文件', description: '系统临时文件和缓存' },
  { key: 'deleted_users', label: '已删除用户', description: '软删除的用户记录' },
  { key: 'expired_sessions', label: '过期会话', description: '已过期的用户会话' },
  { key: 'old_backups', label: '旧备份文件', description: '30天前的备份文件' }
]

const historyFilterOptions = [
  { label: '全部', value: 'all' },
  { label: '备份', value: 'backup' },
  { label: '恢复', value: 'restore' },
  { label: '清理', value: 'cleanup' }
]

// 表格列配置
const historyColumns = [
  { title: '操作类型', dataIndex: 'type', key: 'type' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '状态', dataIndex: 'status', key: 'status', slot: 'status' },
  { title: '执行时间', dataIndex: 'created_at', key: 'created_at' },
  { title: '执行人', dataIndex: 'operator', key: 'operator' },
  { title: '操作', key: 'actions', slot: 'actions', width: '120px' }
]

const backupListColumns = [
  { title: '文件名', dataIndex: 'filename', key: 'filename' },
  { title: '类型', dataIndex: 'backup_type', key: 'backup_type' },
  { title: '大小', dataIndex: 'size', key: 'size', slot: 'size' },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at' },
  { title: '操作', key: 'actions', slot: 'actions', width: '150px' }
]

const { showMessage } = useMessage()

// 方法
const createBackup = async (type: 'full' | 'incremental') => {
  backupLoading.value = true
  try {
    const response = await dataMaintenanceApi.createBackup({
      backup_type: type,
      description: `${type === 'full' ? '完整' : '增量'}备份 - ${new Date().toLocaleString()}`
    })
    
    if (response.success) {
      showMessage.success(`${type === 'full' ? '完整' : '增量'}备份创建成功`)
      await loadBackupInfo()
      await loadMaintenanceHistory()
    }
  } catch (error) {
    showMessage.error('备份创建失败')
    console.error('备份失败:', error)
  } finally {
    backupLoading.value = false
  }
}

const executeCleanup = async () => {
  cleanupLoading.value = true
  try {
    const response = await dataMaintenanceApi.executeCleanup({
      cleanup_types: selectedCleanupTypes.value,
      dry_run: false
    })
    
    if (response.success) {
      showMessage.success('数据清理执行成功')
      showCleanupConfirm.value = false
      await loadCleanupStats()
      await loadMaintenanceHistory()
      selectedCleanupTypes.value = []
    }
  } catch (error) {
    showMessage.error('数据清理执行失败')
    console.error('清理失败:', error)
  } finally {
    cleanupLoading.value = false
  }
}

const executeRestore = async () => {
  if (!selectedBackup.value) return
  
  restoreLoading.value = true
  try {
    const response = await dataMaintenanceApi.restoreBackup({
      backup_id: selectedBackup.value.id,
      create_backup_before_restore: createBackupBeforeRestore.value
    })
    
    if (response.success) {
      showMessage.success('数据恢复执行成功')
      showRestoreConfirm.value = false
      await loadMaintenanceHistory()
    }
  } catch (error) {
    showMessage.error('数据恢复执行失败')
    console.error('恢复失败:', error)
  } finally {
    restoreLoading.value = false
  }
}

const analyzeCleanup = async () => {
  if (selectedCleanupTypes.value.length === 0) {
    showMessage.warning('请先选择清理类型')
    return
  }
  
  try {
    const response = await dataMaintenanceApi.executeCleanup({
      cleanup_types: selectedCleanupTypes.value,
      dry_run: true
    })
    
    if (response.success) {
      const result = response.data
      showMessage.info(`预览完成：将清理 ${result.total_records} 条记录，释放 ${formatFileSize(result.total_size)} 空间`)
    }
  } catch (error) {
    showMessage.error('清理分析失败')
    console.error('分析失败:', error)
  }
}

const updateAutoBackupSetting = async () => {
  try {
    const response = await dataMaintenanceApi.updateAutoBackupConfig({
      enabled: autoBackupEnabled.value,
      interval: autoBackupInterval.value
    })
    
    if (response.success) {
      showMessage.success('自动备份设置已更新')
    }
  } catch (error) {
    showMessage.error('设置更新失败')
    console.error('设置失败:', error)
  }
}

const loadBackupInfo = async () => {
  try {
    const response = await dataMaintenanceApi.getBackupInfo()
    if (response.success) {
      Object.assign(backupInfo, response.data)
    }
  } catch (error) {
    console.error('加载备份信息失败:', error)
  }
}

const loadCleanupStats = async () => {
  try {
    const response = await dataMaintenanceApi.getCleanupStats()
    if (response.success) {
      Object.assign(cleanupStats, response.data)
    }
  } catch (error) {
    console.error('加载清理统计失败:', error)
  }
}

const loadMaintenanceHistory = async () => {
  historyLoading.value = true
  try {
    const response = await dataMaintenanceApi.getMaintenanceHistory({
      type: historyFilter.value === 'all' ? undefined : historyFilter.value,
      page: currentPage.value,
      size: pageSize.value
    })
    
    if (response.success) {
      maintenanceHistory.value = response.data.items
      historyTotal.value = response.data.total
    }
  } catch (error) {
    console.error('加载维护历史失败:', error)
  } finally {
    historyLoading.value = false
  }
}

const loadBackupList = async () => {
  backupListLoading.value = true
  try {
    const response = await dataMaintenanceApi.getBackupList()
    if (response.success) {
      backupList.value = response.data.items
    }
  } catch (error) {
    console.error('加载备份列表失败:', error)
  } finally {
    backupListLoading.value = false
  }
}

const restoreFromBackup = (backup: BackupRecord) => {
  selectedBackup.value = backup
  showRestoreConfirm.value = true
}

const downloadBackup = async (backup: BackupRecord) => {
  try {
    const response = await dataMaintenanceApi.downloadBackup(backup.id)
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    link.download = backup.filename
    link.click()
    window.URL.revokeObjectURL(url)
    
    showMessage.success('备份文件下载成功')
  } catch (error) {
    showMessage.error('备份文件下载失败')
    console.error('下载失败:', error)
  }
}

const deleteBackup = async (backup: BackupRecord) => {
  try {
    const response = await dataMaintenanceApi.deleteBackup(backup.id)
    if (response.success) {
      showMessage.success('备份文件删除成功')
      await loadBackupList()
      await loadBackupInfo()
    }
  } catch (error) {
    showMessage.error('备份文件删除失败')
    console.error('删除失败:', error)
  }
}

const viewMaintenanceDetail = (record: MaintenanceRecord) => {
  // 显示维护详情的逻辑
  console.log('查看维护详情:', record)
}

// 工具方法
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getBackupStatusClass = () => {
  if (!backupInfo.lastBackup) return 'status-none'
  const lastBackupDate = new Date(backupInfo.lastBackup)
  const now = new Date()
  const daysDiff = (now.getTime() - lastBackupDate.getTime()) / (1000 * 3600 * 24)
  
  if (daysDiff <= 1) return 'status-good'
  if (daysDiff <= 7) return 'status-warning'
  return 'status-danger'
}

const getStatusClass = (status: string) => {
  return {
    'status-completed': status === 'completed',
    'status-running': status === 'running',
    'status-failed': status === 'failed',
    'status-pending': status === 'pending'
  }
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    completed: '已完成',
    running: '执行中',
    failed: '失败',
    pending: '等待中'
  }
  return statusMap[status] || status
}

const getCleanupTypeLabel = (type: string) => {
  const option = cleanupOptions.find(opt => opt.key === type)
  return option?.label || type
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    loadBackupInfo(),
    loadCleanupStats(),
    loadMaintenanceHistory()
  ])
})

// 监听备份列表弹窗显示
watch(() => showBackupList.value, (visible) => {
  if (visible) {
    loadBackupList()
  }
})
</script>

<style scoped lang="scss">
.data-maintenance-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 24px;
    
    h1 {
      margin: 0 0 8px 0;
      font-size: 28px;
      font-weight: 600;
      color: #1d1d1f;
    }
    
    .subtitle {
      margin: 0;
      color: #6e6e73;
      font-size: 16px;
    }
  }
  
  .section-content {
    padding: 16px 0;
  }
  
  // 备份管理样式
  .backup-status {
    margin-bottom: 20px;
    
    .status-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid #f2f2f7;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        font-weight: 500;
        color: #1d1d1f;
      }
      
      .value {
        font-weight: 600;
        
        &.status-good { color: #30d158; }
        &.status-warning { color: #ff9f0a; }
        &.status-danger { color: #ff3b30; }
        &.status-none { color: #8e8e93; }
      }
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
    flex-wrap: wrap;
    
    .backup-btn {
      flex: 1;
      min-width: 120px;
      
      i {
        margin-right: 8px;
      }
    }
  }
  
  .auto-backup-setting {
    padding: 16px;
    background: #f2f2f7;
    border-radius: 12px;
    
    .setting-item {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 12px;
      cursor: pointer;
      
      input[type="checkbox"] {
        width: 16px;
        height: 16px;
      }
    }
    
    .interval-select {
      width: 100%;
    }
  }
  
  // 数据清理样式
  .cleanup-stats {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    
    .stat-item {
      flex: 1;
      text-align: center;
      padding: 16px;
      background: #f2f2f7;
      border-radius: 12px;
      
      .stat-number {
        font-size: 24px;
        font-weight: 600;
        color: #007aff;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 12px;
        color: #6e6e73;
      }
    }
  }
  
  .cleanup-options {
    margin-bottom: 20px;
    
    .cleanup-option {
      display: flex;
      align-items: flex-start;
      gap: 8px;
      padding: 8px 0;
      cursor: pointer;
      
      input[type="checkbox"] {
        width: 16px;
        height: 16px;
        margin-top: 2px;
      }
      
      .option-text {
        flex: 1;
        
        small {
          display: block;
          color: #6e6e73;
          font-size: 12px;
          margin-top: 2px;
        }
      }
    }
  }
  
  .cleanup-actions {
    display: flex;
    gap: 12px;
    
    .cleanup-btn {
      flex: 1;
      
      i {
        margin-right: 8px;
      }
    }
  }
  
  // 维护历史样式
  .maintenance-history {
    margin-top: 24px;
    
    .history-controls {
      display: flex;
      gap: 12px;
      margin-bottom: 16px;
      
      .filter-select {
        width: 200px;
      }
      
      .refresh-btn {
        i {
          margin-right: 8px;
        }
      }
    }
  }
  
  // 状态样式
  .status-completed { color: #30d158; }
  .status-running { color: #007aff; }
  .status-failed { color: #ff3b30; }
  .status-pending { color: #ff9f0a; }
  
  // 弹窗样式
  .confirm-content {
    text-align: center;
    
    .warning-icon {
      font-size: 48px;
      margin-bottom: 16px;
    }
    
    .warning-text {
      margin-bottom: 20px;
      line-height: 1.5;
      color: #6e6e73;
    }
    
    .cleanup-summary, .backup-info {
      text-align: left;
      padding: 16px;
      background: #f2f2f7;
      border-radius: 8px;
      margin-bottom: 16px;
      
      ul {
        margin: 8px 0 0 16px;
        
        li {
          margin-bottom: 4px;
        }
      }
    }
    
    .restore-option {
      display: flex;
      align-items: center;
      gap: 8px;
      justify-content: center;
      cursor: pointer;
      
      input[type="checkbox"] {
        width: 16px;
        height: 16px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .data-maintenance-container {
    padding: 16px;
    
    .action-buttons, .cleanup-actions {
      flex-direction: column;
      
      .backup-btn, .cleanup-btn {
        min-width: unset;
      }
    }
    
    .cleanup-stats {
      flex-direction: column;
    }
    
    .history-controls {
      flex-direction: column;
      
      .filter-select {
        width: 100%;
      }
    }
  }
}
</style>